package com.wekri.wechat4j.util;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

/**
 * @author liuweiguo.
 */
public class Validator {
    /**
     * 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     */
    private String signature;
    /**
     * 时间戳
     */
    private String timestamp;
    /**
     * 随机数
     */
    private String nonce;
    /**
     * 微信公众号里“服务器配置”中的token
     */
    private String token;

    public Validator(String signature, String timestamp, String nonce, String token) {
        this.signature = signature;
        this.timestamp = timestamp;
        this.nonce = nonce;
        this.token = token;
    }

    public boolean checkSignature() {
        if (StringUtils.isAnyEmpty(token, timestamp, nonce, signature)) {
            return false;
        }
        String[] sa = {this.token, this.timestamp, this.nonce};
        Arrays.sort(sa);
        String sortStr = sa[0] + sa[1] + sa[2];

        return DigestUtils.sha1Hex(sortStr).equals(this.signature);
    }
}
